// FmDetail.js
let audioContext = null;

Page({
  data: {
    fm: {},
    isPlaying: false,
    duration: 0,
    currentTime: 0
  },

  onLoad(options) {
    this.initAudioContext();
    this.loadFmData(options.id);
  },

  onShow() {
    if (!audioContext) {
      this.initAudioContext();
    }
  },

  onHide() {
    if (audioContext) {
      audioContext.pause();
      this.setData({ isPlaying: false });
    }
  },

  onUnload() {
    this.destroyAudioContext();
  },

  initAudioContext() {
    audioContext = wx.createInnerAudioContext();
    this.setupAudioContext();
  },

  destroyAudioContext() {
    if (audioContext) {
      audioContext.stop();
      audioContext.destroy();
      audioContext = null;
    }
  },

  loadFmData(id) {
    wx.request({
      url: `http://localhost:8080/fm/getFM/${id}`,
      success: res => {
        console.log(res.data.data);
        this.setData({ fm: res.data.data });
        
        if (audioContext && this.data.fm.fmUrl) {
          audioContext.src = `http://localhost:8080/fm/downaudio?fileName=${this.data.fm.fmUrl}`;
          console.log(audioContext.src);
          
          wx.showToast({
            title: '音频已就绪，点击播放',
            icon: 'none',
            duration: 2000
          });
        }
      }
    });
  },

  setupAudioContext() {
    if (!audioContext) return;

    audioContext.onCanplay(() => {
      this.setData({ duration: audioContext.duration });
    });

    audioContext.onTimeUpdate(() => {
      this.setData({ currentTime: audioContext.currentTime });
    });

    audioContext.onEnded(() => {
      this.setData({ isPlaying: false, currentTime: 0 });
    });

    audioContext.onError((res) => {
      console.error('音频播放错误', res);
      wx.showToast({
        title: '音频加载失败，请重试',
        icon: 'none'
      });
    });
  },

  playPause: function() {
    if (!audioContext) return;

    if (this.data.isPlaying) {
      audioContext.pause();
      wx.showToast({ title: '已暂停', icon: 'none', duration: 1000 });
    } else {
      audioContext.play();
      wx.showToast({ title: '开始播放', icon: 'none', duration: 1000 });
    }
    this.setData({ isPlaying: !this.data.isPlaying });
  },

  sliderChange: function(e) {
    if (!audioContext) return;
    const position = e.detail.value;
    audioContext.seek(position);
    this.setData({ currentTime: position });
  },

  previousSong: function() {
    // 实现上一首歌曲逻辑
    console.log("Previous song functionality not implemented");
    wx.showToast({
      title: '功能未实现',
      icon: 'none',
      duration: 1000
    });
  },

  nextSong: function() {
    // 实现下一首歌曲逻辑
    console.log("Next song functionality not implemented");
    wx.showToast({
      title: '功能未实现',
      icon: 'none',
      duration: 1000
    });
  },

  formatTime: function(time) {
    const minutes = Math.floor(time / 60);
    const seconds = Math.floor(time % 60);
    return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
  }
});